/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ManVenta.java
 *
 * Created on 17/03/2011, 08:20:38 AM
 */

package com.catosist.run.application.venta;

import com.catosist.run.application.Util.ButtonTabComponent;
import com.catosist.run.business.gestorComprobanteDetalle.GestorComprobanteDetalle;
import com.catosist.run.business.gestorConstante.GestorConstante;
import com.catosist.run.business.gestorcliente.GestorCliente;
import com.catosist.run.business.gestorcomprobante.GestorComprobante;
import com.catosist.run.business.gestorruta.GestorRuta;
import com.catosist.run.business.gestorvehiculo.GestorVehiculo;
import com.catosist.run.business.gestorviaje.GestorViaje;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException;

/**
 *
 * @author igorov
 */
public class ManVenta extends javax.swing.JFrame {

    /** Creates new form ManVenta */
    public ManVenta() {
        initComponents();
        iniciar();
    }

    public ManVenta(GestorComprobante gestorComprobante, GestorCliente gestorCliente,
            GestorViaje gestorViaje, GestorComprobanteDetalle gestorComprobanteDetalle,
            GestorConstante gestorConstante) {
        this.gestorComprobante = gestorComprobante;
        this.gestorCliente = gestorCliente;

        this.gestorComprobanteDetalle = gestorComprobanteDetalle;
        this.gestorConstante = gestorConstante;

        this.gestorViaje = gestorViaje;
        initComponents();
//        gestionVentasFacturas = new GestionVentasFacturas(gestorComprobante, gestorCliente);
//        gestionVentasBoletas = new GestionVentasBoletas(gestorComprobante);
    }



    public JPanel getPanel(){
        return this.jPanel1;
    }

    public void agregaPestanha(JPanel panel, String titulo) {
        this.tabWork.removeAll();
        this.tabWork.add(titulo, panel);
        this.tabWork.setSelectedIndex(this.tabWork.getTabCount() - 1);
        ButtonTabComponent pestana = new ButtonTabComponent("componente", this.tabWork);
        this.tabWork.setTabComponentAt(this.tabWork.getTabCount() - 1, pestana);
    }

    public void iniciar() {
//        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
//        gestorComprobante = (GestorComprobante) ctx.getBean("gestorComprobante");
//        gestorRuta = (GestorRuta) ctx.getBean("gestorRuta");
//        gestionVentasFacturas = new GestionVentasFacturas(gestorComprobante, gestorCliente);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        btnVerFacturas = new javax.swing.JButton();
        btnNuevo = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnVerBoletas = new javax.swing.JButton();
        btnContratos = new javax.swing.JButton();
        tabWork = new javax.swing.JTabbedPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.catosist.run.application.desktopapplication.DesktopApplication.class).getContext().getResourceMap(ManVenta.class);
        btnVerFacturas.setText(resourceMap.getString("btnVerFacturas.text")); // NOI18N
        btnVerFacturas.setName("btnVerFacturas"); // NOI18N
        btnVerFacturas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerFacturasActionPerformed(evt);
            }
        });

        btnNuevo.setText(resourceMap.getString("btnNuevo.text")); // NOI18N
        btnNuevo.setName("btnNuevo"); // NOI18N
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEditar.setText(resourceMap.getString("btnEditar.text")); // NOI18N
        btnEditar.setName("btnEditar"); // NOI18N
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnEliminar.setText(resourceMap.getString("btnEliminar.text")); // NOI18N
        btnEliminar.setName("btnEliminar"); // NOI18N
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnVerBoletas.setText(resourceMap.getString("btnVerBoletas.text")); // NOI18N
        btnVerBoletas.setName("btnVerBoletas"); // NOI18N
        btnVerBoletas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerBoletasActionPerformed(evt);
            }
        });

        btnContratos.setText(resourceMap.getString("btnContratos.text")); // NOI18N
        btnContratos.setName("btnContratos"); // NOI18N
        btnContratos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnContratosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnVerFacturas)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnVerBoletas)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnContratos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEditar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEliminar)
                .addContainerGap(36, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnVerFacturas)
                    .addComponent(btnVerBoletas)
                    .addComponent(btnContratos)
                    .addComponent(btnNuevo)
                    .addComponent(btnEditar)
                    .addComponent(btnEliminar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N

        tabWork.setName("tabWork"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 962, Short.MAX_VALUE)
                    .addComponent(tabWork, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 962, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tabWork, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnVerFacturasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerFacturasActionPerformed
        gestionVentas = new GestionVentas(gestorComprobante, gestorCliente, 'f');
        agregaPestanha(gestionVentas.getPanel(), "Ventas por factura");
    }//GEN-LAST:event_btnVerFacturasActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        DialogVenta dialogVenta = new DialogVenta(this, true, gestorComprobante, gestorCliente, 0, gestorViaje, gestorComprobanteDetalle,
                                    gestorConstante);
        dialogVenta.setLocationRelativeTo(this);
        dialogVenta.setVisible(true);
//        this.gestionVentasFacturas.refresh();
        if (dialogVenta.getTipoComprobante().compareTo("factura") == 0) {
            System.out.println("Creado una factura");
            this.gestionVentas.recuperarComprobantesFacturas();
        }
        else{
            System.out.println("Creado una boleta");
            this.gestionVentas.recuperarComprobantesBoletas();
        }
//        this.gestionVentasFacturas.recuperarComprobantes();

        this.gestionVentas.refresh();
//        this.gestionVentasBoletas.refresh();
}//GEN-LAST:event_btnNuevoActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        try {
            int i = this.gestionVentas.getSelectedId();
            
            DialogVenta dialogVenta = new DialogVenta(this, true, gestorComprobante, gestorCliente, i, gestorViaje, gestorComprobanteDetalle,
                                    gestorConstante);
            
            dialogVenta.setLocationRelativeTo(this);
            dialogVenta.setVisible(true);
            
            if (dialogVenta.getTipoComprobante().compareTo("Factura") == 0) {
                this.gestionVentas.recuperarComprobantesFacturas();
            } else {
                this.gestionVentas.recuperarComprobantesBoletas();
            }
            this.gestionVentas.refresh();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
            JOptionPane.showMessageDialog(this, "Debe seleccionar un comprobante existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
        System.out.println("Boton editar");
}//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        try {
            int i = this.gestionVentas.getSelectedId();
            int result = JOptionPane.showConfirmDialog(this, "Realmente desea eliminar el registro?");
            if (result == JOptionPane.YES_OPTION) {
                gestorComprobante.deleteById(i);
                gestionVentas.refresh();
            }
        }catch (ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar una ruta existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }

        catch (HibernateObjectRetrievalFailureException e) {
            JOptionPane.showMessageDialog(this, "No se puede eliminar la ruta", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
}//GEN-LAST:event_btnEliminarActionPerformed

    private void btnVerBoletasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerBoletasActionPerformed
        // TODO add your handling code here:
        gestionVentas = new GestionVentas(gestorComprobante, gestorCliente, 'b');
        agregaPestanha(gestionVentas.getPanel(), "Ventas por boleta");
    }//GEN-LAST:event_btnVerBoletasActionPerformed

    private void btnContratosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnContratosActionPerformed
        // TODO add your handling code here:
        gestionVentas = new GestionVentas(gestorComprobante, gestorCliente, 'c');
        agregaPestanha(gestionVentas.getPanel(), "Ventas por Guias de contrato al cliente");
    }//GEN-LAST:event_btnContratosActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ManVenta().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnContratos;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JButton btnVerBoletas;
    private javax.swing.JButton btnVerFacturas;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane tabWork;
    // End of variables declaration//GEN-END:variables
    private GestionVentas gestionVentas;
//    private ApplicationContext ctx;
    private GestorComprobante gestorComprobante;
    private GestorCliente gestorCliente;

    private GestorViaje gestorViaje;

    private GestorComprobanteDetalle gestorComprobanteDetalle;
    private GestorConstante gestorConstante;
}
